package services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;

import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import DataAccess.DeviceDA;
import DataAccess.NguoiDungDA;
import DataAccess.NhomDA;
import DataAccess.NhomNguoiDungDA;
import DataAccess.TinNhanDA;

import pojo.DevicePOJO;
import pojo.NguoiDungPOJO;
import pojo.NhomNguoiDungPOJO;
import pojo.NhomPOJO;
import pojo.PairValue;
import pojo.TinNhanPOJO;
import util.ClientSender;
import util.Common;
import util.GCMSender;
import util.XMLBuidler;

/**
 * Servlet implementation class HeThong
 */
// @WebServlet("/HeThong")
@WebServlet(name = "HeThong", urlPatterns = { "/HeThong" })
public class HeThongServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @throws ServletException
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// super.doGet(request, response);
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {

			String cmd = getParameter(request, Protocol.CMD);

			if (cmd != null) {
				System.out.println("CMD=" + cmd);
				if (cmd.equals(Protocol.DANG_KY_DEVICE)) {
					String regID = getParameter(request, Protocol.REG_ID);
					String tenDangNhap = "phu";
					DeviceDA da = new DeviceDA();
					DevicePOJO dv = new DevicePOJO(regID, tenDangNhap);
					if (da.insert(dv)) {
						out.print(true);
						System.out.print(Protocol.DANG_KY_DEVICE + " regId= " + regID);
					} else {
						out.print(false);
					}
				} else if (cmd.equals(Protocol.DANG_NHAP)) {
					String tenDangNhap, matKhau, regID;
					tenDangNhap = getParameter(request, Protocol.TEN_DANG_NHAP);
					matKhau = getParameter(request, Protocol.MAT_KHAU);
					regID = getParameter(request, Protocol.REG_ID);
					NguoiDungDA da = new NguoiDungDA();
					NguoiDungPOJO nd = da.get(tenDangNhap);
					if (nd != null && nd.getMatKhau().equals(matKhau)) {
						// Nếu regId hiện tại ko phải của tài khoản này thì cập
						// nhật lại
						if (!nd.getDeviceID().equals(regID)) {
							da.resetDeviceID(regID);
						}
						da.updateDeiveID(tenDangNhap, regID);
						final long timeStamp = System.currentTimeMillis();
						long diffDay = (timeStamp - nd.getLastRequest()) / (1000 * 60 * 60 * 24);
						nd.setLastRequest(diffDay);
						Document doc = XMLBuidler.BuildXML("Root");
						doc.getFirstChild().appendChild(nd.createContactXMLElement(doc));
						out.print(XMLBuidler.docToString(doc));
						System.out.println(XMLBuidler.docToString(doc));

						da.updateDeiveLastRequest(tenDangNhap, timeStamp);

					} else {
						out.print(false);
					}
				} else if (cmd.equals(Protocol.DANH_SACH_NHOM)) {
					String tenDangNhap = getParameter(request, Protocol.TEN_DANG_NHAP);
					String contact = XMLBuidler.getContact(tenDangNhap);
					out.print(contact);
					System.out.println(contact);
				} else if (cmd.equals(Protocol.LAY_TIN_NHAN)) {
					String nguoiNhan = getParameter(request, Protocol.NGUOI_DUNG);
					TinNhanDA da = new TinNhanDA();
					ArrayList<TinNhanPOJO> lstTinNhan = da.getByNguoiNhan(nguoiNhan, 0);
					String data = XMLBuidler.layTinNhan(lstTinNhan);
					out.print(data);
					System.out.println(data);
				} else if (cmd.equals(Protocol.GUI_TIN_NHAN)) {
					String nguoiGui = getParameter(request, Protocol.NGUOI_GUI);
					String nguoiNhan = getParameter(request, Protocol.NGUOI_NHAN);
					String noiDung = getParameter(request, Protocol.NOI_DUNG);
					String loai = getParameter(request, Protocol.MSG_TYPE, "0");

					TinNhanPOJO tinNhan = new TinNhanPOJO();

					tinNhan.setNguoiGui(nguoiGui);
					tinNhan.setNguoiNhan(nguoiNhan);
					tinNhan.setNoiDung(noiDung);
					tinNhan.setTinhTrang(0);
					tinNhan.setLoai(Integer.parseInt(loai));

					TinNhanDA tinNhanDA = new TinNhanDA();
					tinNhanDA.insert(tinNhan);

					ArrayList<PairValue> params = new ArrayList<PairValue>();
					params.add(new PairValue(Protocol.CMD, Protocol.GUI_TIN_NHAN));
					params.add(new PairValue(Protocol.NGUOI_GUI, nguoiGui));
					params.add(new PairValue(Protocol.NOI_DUNG, noiDung));
					params.add(new PairValue(Protocol.MSG_TYPE, loai));
					params.add(new PairValue(Protocol.ID, tinNhan.getId() + ""));
					// NguoiDungPOJO nd = new NguoiDungDA().get(nguoiNhan);
					//
					// ClientSender.send(nd.getDeviceID(), params,
					// Protocol.MAX_TIME);
					//
					String regID = new NguoiDungDA().getDeviceID(nguoiNhan);
					ClientSender.send(regID, params, Protocol.MAX_TIME);

					System.out.println("GUI_TIN_NHAN: bn.gui=" + nguoiGui + "bn.nhan=" + nguoiNhan + "noidung="
							+ noiDung + "type=" + loai);
				} else if (cmd.equals(Protocol.SO_LUONG_TIN_NHAN_OFFLINE)) {
					String nguoiNhan = getParameter(request, Protocol.NGUOI_DUNG);
					int soLuong = new TinNhanDA().soLuongOffline(nguoiNhan);
					out.print(soLuong);
				} else if (cmd.equals(Protocol.XOA_TIN_NHAN)) {
					int id = Integer.parseInt(getParameter(request, Protocol.ID));
					boolean rs = new TinNhanDA().capNhatDaDoc(id);
					out.print(rs);
				} else if (cmd.equals(Protocol.DONG_Y_VAO_NHOM)) {

					int idNhom = Integer.parseInt(getParameter(request, Protocol.ID_NHOM));
					int idTinNhan = Integer.parseInt(getParameter(request, Protocol.ID));
					String nguoiDung = getParameter(request, Protocol.NGUOI_DUNG);

					NhomNguoiDungPOJO nhomNguoi = new NhomNguoiDungPOJO();
					nhomNguoi.setIdNhom(idNhom);
					nhomNguoi.setNguoiDung(nguoiDung);
					new NhomNguoiDungDA().insert(nhomNguoi);

					ArrayList<NguoiDungPOJO> lstThanhVien = new NguoiDungDA().getNguoiDungCuaNhom(idNhom);
					ArrayList<String> lstDevice = Common.retrieveRegId(lstThanhVien);

					ArrayList<PairValue> params = new ArrayList<PairValue>();
					params.add(new PairValue(Protocol.CMD, Protocol.CAP_NHAT_CONTACT));
					params.add(new PairValue(Protocol.ID_NHOM, idNhom + ""));
					ClientSender.send(lstDevice, params, Protocol.MAX_TIME);

					params.remove(0);
					params.add(new PairValue(Protocol.CMD, Protocol.CAP_NHAT_SUBJECT));

					ClientSender.send(lstDevice, params, Protocol.MAX_TIME);
					new TinNhanDA().capNhatDaDoc(idTinNhan);
				} else if (cmd.equals(Protocol.TIN_NHAN_BROADCAST)) {
					int idNhom = Integer.parseInt(getParameter(request, Protocol.ID_NHOM));
					String nguoiGui = getParameter(request, Protocol.NGUOI_GUI);
					String noiDung = getParameter(request, Protocol.NOI_DUNG);
					int loai = 0;

					ArrayList<NguoiDungPOJO> lstNguoiDung = new NguoiDungDA().getNguoiDungCuaNhom(idNhom);

					for (int i = 0; i < lstNguoiDung.size(); i++) {
						if (!lstNguoiDung.get(i).getTenDangNhap().equals(nguoiGui)) {
							TinNhanPOJO tinNhan = new TinNhanPOJO();
							tinNhan.setNguoiGui(nguoiGui);
							tinNhan.setNguoiNhan(lstNguoiDung.get(i).getTenDangNhap());
							tinNhan.setNoiDung(noiDung);
							tinNhan.setTinhTrang(0);
							tinNhan.setLoai(loai);

							TinNhanDA tinNhanDA = new TinNhanDA();
							tinNhanDA.insert(tinNhan);

							ArrayList<PairValue> params = new ArrayList<PairValue>();
							params.add(new PairValue(Protocol.CMD, Protocol.GUI_TIN_NHAN));
							params.add(new PairValue(Protocol.NGUOI_GUI, nguoiGui));
							params.add(new PairValue(Protocol.NOI_DUNG, noiDung));
							params.add(new PairValue(Protocol.MSG_TYPE, loai+""));
							params.add(new PairValue(Protocol.ID, tinNhan.getId() + ""));
							
							ClientSender.send(lstNguoiDung.get(i).getDeviceID(), params,30);
						}
					}

				}
			}

		} catch (Exception e) {
			out.print(Protocol.SERVER_ERROR);
			if (Protocol.DEBUG == 1) {
				e.printStackTrace(out);
			}
			System.out.print("Lỗi: " + e.getMessage());
		}
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		doGet(request, response);
	}

}
